package com.mhc.suzuki.controller;

import com.alibaba.fastjson.JSON;
import com.mhc.haval.api.dto.DepartmentDTO;
import com.mhc.haval.api.service.IStaffDeptService;
import com.mhc.haval.security.model.Role;
import com.mhc.haval.security.model.User;
import com.mhc.suzuki.constant.ApplyTypeEnum;
import com.mhc.suzuki.constant.ApprovalResultEnum;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.constant.RoleTypeEnum;
import com.mhc.suzuki.dal.query.OrderQuery;
import com.mhc.suzuki.form.AuditListForm;
import com.mhc.suzuki.service.AuditTaskService;
import com.mhc.suzuki.service.OrderAuditApplyService;
import com.mhc.suzuki.vo.AuditInfoVO;
import com.mhc.suzuki.vo.DepartmentVO;
import com.mhc.suzuki.vo.ModifyInfoVO;
import com.mhc.suzuki.vo.OrderAuditApplyVO;
import com.subaru.common.entity.BizResult;
import com.subaru.common.util.BeanCopierUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 审核信息
 * Created by kanon on 17/8/29 17:18.
 */
@Slf4j
@RestController
@RequestMapping(value = "/audit")
public class OrderAuditTaskController {

    @Autowired
    private OrderAuditApplyService orderAuditApplyService;
    @Autowired
    private IStaffDeptService staffDeptService;

    @Autowired
    AuditTaskService auditTaskService;

    @ApiOperation(value = "审核信息", notes = "")
    @RequestMapping(value = "/tasks/{orderNO}", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNO", value = "订单号", paramType = "path", required = true, dataType = "String"),
    })
    public BizResult<AuditInfoVO> queryOrderAuditTaskList(@PathVariable String orderNO ,@AuthenticationPrincipal User logedUser) {
        try {
            /**获取角色code**/
            String roleCode =logedUser.getRoleList().get(0).getRoleCode();
            //审核历史
            List<OrderAuditApplyVO> orderAuditApplyVOList = orderAuditApplyService.queryOrderAuditApplyList(
                    orderNO, ApplyTypeEnum.LOAN_APPLY.getCode(), null,roleCode);
            //资料修改历史
            List<OrderAuditApplyVO> modifyRecordOrderAuditApplyVOList = orderAuditApplyService.queryOrderAuditApplyList(
                    orderNO, ApplyTypeEnum.MODIFY_APPLY.getCode(), null,roleCode);
            //通融审核历史
            List<OrderAuditApplyVO> accommodateOrderAuditApplyVOList = orderAuditApplyService.queryOrderAuditApplyList(
                    orderNO, ApplyTypeEnum.ACCOM_APPLY.getCode(), null,roleCode);
            //打款驳回历史
            List<OrderAuditApplyVO> rejectPaymentOrderAuditApplyVOList = orderAuditApplyService.queryOrderAuditApplyList(
                    orderNO, ApplyTypeEnum.PAYMENT_REQUEST_APPLY.getCode(), ApprovalResultEnum.REJECT.getCode(),roleCode);

            AuditInfoVO auditInfoVO = new AuditInfoVO();
            auditInfoVO.setOrderAuditApplyVOList(orderAuditApplyVOList);
            auditInfoVO.setModifyRecordOrderAuditApplyVOList(modifyRecordOrderAuditApplyVOList);
            auditInfoVO.setAccommodateOrderAuditApplyVOList(accommodateOrderAuditApplyVOList);
            auditInfoVO.setRejectPaymentOrderAuditApplyVOList(rejectPaymentOrderAuditApplyVOList);
            return BizResult.create(auditInfoVO, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
        } catch (Exception e) {
            log.error("Query order audit task list exception: ", e);
            return BizResult.create("", "查询贷款审核信息异常");
        }
    }

    @ApiOperation(value = "资料修改信息", notes = "")
    @RequestMapping(value = "/modifyInfo/{orderNO}", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNO", value = "订单号", paramType = "path", required = true, dataType = "String"),
    })
    public BizResult<ModifyInfoVO> queryModifyInfo(@PathVariable String orderNO) {
        try {
            //资料修改记录
            ModifyInfoVO modifyInfoVO = orderAuditApplyService.queryApplyInfo(orderNO, ApplyTypeEnum.MODIFY_APPLY.getCode());

            return BizResult.create(modifyInfoVO, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
        } catch (Exception e) {
            log.error("queryModifyInfo exception: ", e);
            return BizResult.create("", "查询资料修改审核信息异常");
        }
    }

    @ApiOperation(value = "通融信息", notes = "")
    @RequestMapping(value = "/accomInfo/{orderNO}", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNO", value = "订单号", paramType = "path", required = true, dataType = "String"),
    })
    public BizResult<ModifyInfoVO> queryAccomInfo(@AuthenticationPrincipal User logedUser, @PathVariable String orderNO) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            try {
                ModifyInfoVO modifyInfoVO = null;
                List<Role> roleList = logedUser.getRoleList();
                if (roleList != null && roleList.size() > 0) {
                    for (Role role : roleList) {
                        //如果是不是业务员角色,取通融申请数据
                        if (!(RoleTypeEnum.ROLE_SALESMAN.getCode().equals(role.getRoleCode()) || RoleTypeEnum.ROLE_SPSALESMAN.getCode().equals(role.getRoleCode()))) {
                            //通融信息记录,打款驳回
                            modifyInfoVO = orderAuditApplyService.queryApplyInfo(orderNO, ApplyTypeEnum.ACCOM_APPLY.getCode());
                        }
                        //如果是业务员角色(sp业务员),取贷款驳回数据
                        if (RoleTypeEnum.ROLE_SALESMAN.getCode().equals(role.getRoleCode()) || RoleTypeEnum.ROLE_SPSALESMAN.getCode().equals(role.getRoleCode())) {
                            //通融信息记录,打款驳回
                            modifyInfoVO = orderAuditApplyService.queryApplyInfo(orderNO, ApplyTypeEnum.LOAN_APPLY.getCode());
                        }
                    }
                    return BizResult.create(modifyInfoVO, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());

                } else {
                    return BizResult.create(ErrorCodeEnum.NO_AUTH.getErrCode(), ErrorCodeEnum.NO_AUTH.getErrMsg());
                }
            } catch (Exception e) {
                log.error("queryAccomInfo exception: ", e);
                return BizResult.create("", "查询通融申请审核信息异常");
            }
        } else {
            return BizResult.create(ErrorCodeEnum.SYS_ERROR.getErrCode(), "用户未登录");
        }

    }

    /**
     * 获取部门列表
     *
     * @param parentDeptId 上级部门ID
     * @param logedUser    登陆信息
     * @return
     */
    @ApiOperation(value = "获取部门列表", httpMethod = "GET", notes = "根据查询条件获取部门列表")
    @RequestMapping(value = {"/getDeptList"}, method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentDeptId", value = "上级部门ID", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "companyNo", value = "公司ID", required = true, paramType = "query", dataType = "Long")
    })
    public BizResult getDeptList(@RequestParam(value = "parentDeptId", required = false, defaultValue = "") Long parentDeptId,
                                 @AuthenticationPrincipal User logedUser) {
        try {
            List<DepartmentDTO> departmentList = staffDeptService.queryByDeptList(parentDeptId, logedUser.getCompanyNo());
            /**将DO转化成VO**/
            List<DepartmentVO> deptList = new ArrayList<>();
            for (DepartmentDTO departmentDTO : departmentList) {
                DepartmentVO departmentVO = new DepartmentVO();
                BeanCopierUtil.copy(departmentDTO, departmentVO);
                deptList.add(departmentVO);
            }
            log.info("获取部门列表成功,List:{}", JSON.toJSONString(deptList));
            if (!CollectionUtils.isEmpty(deptList)) {
                return BizResult.create(deptList, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
            } else {
                return BizResult.create(null, ErrorCodeEnum.NO_DATA.getErrCode(), ErrorCodeEnum.NO_DATA.getErrMsg());
            }
        } catch (Exception e) {
            log.error("获取部门列表异常: " + e.getMessage(), e);
            return BizResult.create(ErrorCodeEnum.SELECT_FAILURE.getErrCode(), ErrorCodeEnum.SELECT_FAILURE.getErrMsg());
        }
    }


    /**
     * 获取我的审核待办列表
     *
     * @param aduAuditListForm
     * @return
     */
    @ApiOperation(value = "我的审核待办列表", notes = "我的审核待办列表")
    @ApiImplicitParam(name = "aduAuditListForm", value = "订单列表form", required = false, dataType = "AuditListForm")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object getAuditTaskList(@AuthenticationPrincipal User logedUser, AuditListForm aduAuditListForm) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            try {
                OrderQuery orderQuery = new OrderQuery();
                Optional<AuditListForm> orderListFormOptional = Optional.ofNullable(aduAuditListForm);
                Map<String, Object> queryMap = new HashMap<>(64);
                //设置查询条件
                if (orderListFormOptional.isPresent()) {
                    if (aduAuditListForm.getPageNO() == null || aduAuditListForm.getPageNO() == 0) {
                        aduAuditListForm.setPageNO(1);
                    }
                    if (aduAuditListForm.getPageSize() == null || aduAuditListForm.getPageSize() == 0) {
                        aduAuditListForm.setPageSize(10);
                    }
                    orderQuery.setPageNo(aduAuditListForm.getPageNO());
                    orderQuery.setPageSize(aduAuditListForm.getPageSize());
                    queryMap.put("pageNo", orderQuery.getPageNo());
                    queryMap.put("pageSize", orderQuery.getPageSize());
                    queryMap.put("pageOffset", orderQuery.getPageOffset());
                    Optional<String> beginDateOptional = Optional.ofNullable(aduAuditListForm.getGmtCreateBegin());
                    Optional<String> endDateOptional = Optional.ofNullable(aduAuditListForm.getGmtCreateEnd());
                    if (beginDateOptional.isPresent() && !"".equals(beginDateOptional.get())) {
                        queryMap.put("gmtCreateBegin", beginDateOptional.get());
                    }
                    if (endDateOptional.isPresent() && !"".equals(endDateOptional.get())) {
                        queryMap.put("gmtCreateEnd", endDateOptional.get());
                    }
                }
                queryMap.put("keyword", aduAuditListForm.getKeyword());
                queryMap.put("staffName", aduAuditListForm.getStaffName());
                queryMap.put("loanBankId", aduAuditListForm.getLoanBankId());
                queryMap.put("loanBankIdList", aduAuditListForm.getLoanBankIdList());
                queryMap.put("deptId", aduAuditListForm.getDeptId());
                queryMap.put("applyType", aduAuditListForm.getApplyType());
                queryMap.put("applyTypeList", aduAuditListForm.getApplyTypeList());
                BizResult result = BizResult.create(auditTaskService.getAuditTaskList(logedUser.getStaffId(), queryMap), true, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
                result.setTotalCount(((List) result.getData()).size());
                if (aduAuditListForm.getPageSize() != null) {
                    result.setPageSize(aduAuditListForm.getPageSize());
                    result.setPageNo(aduAuditListForm.getPageNO());
                }
                return result;
            } catch (Exception e) {
                log.error("ERROR IN getAuditTaskList", e);
                return BizResult.create(ErrorCodeEnum.SYS_ERROR.getErrCode(), e.getMessage());
            }
        } else {
            return BizResult.create(ErrorCodeEnum.NOT_LOGIN.getErrCode(), ErrorCodeEnum.NOT_LOGIN.getErrMsg());
        }
    }

    /**
     * 获取订单审核进度
     *
     * @param orderNo
     * @return
     */
    @ApiOperation(value = "获取订单审核进度", notes = "获取订单审核进度")
    @ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, paramType = "path", dataType = "String")
    @RequestMapping(value = "/status/list/{orderNo}", method = RequestMethod.GET)
    public Object getAuditStatusList(@AuthenticationPrincipal User logedUser, @PathVariable String orderNo) {
        try {
            return BizResult.create(auditTaskService.getAuditStatusList(logedUser, orderNo), true, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
        } catch (Exception e) {
            log.error("ERROR IN getAuditStatusList", e);
            return BizResult.create(ErrorCodeEnum.SYS_ERROR.getErrCode(), e.getMessage());
        }
    }

    /**
     * 获取GPS确认列表
     * 资产保全部任务池
     * @param logedUser
     * @param aduAuditListForm
     * @return
     */
    @ApiOperation(value = "GPS确认列表", notes = "GPS确认列表")
    @ApiImplicitParam(name = "aduAuditListForm", value = "订单列表form", required = false, dataType = "AuditListForm")
    @RequestMapping(value = "/getGPSTaskList", method = RequestMethod.GET)
    public Object getGPSTaskList(@AuthenticationPrincipal User logedUser, AuditListForm aduAuditListForm) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            try {
                OrderQuery orderQuery = new OrderQuery();
                Optional<AuditListForm> orderListFormOptional = Optional.ofNullable(aduAuditListForm);
                Map<String, Object> queryMap = new HashMap<>(64);
                //设置查询条件
                if (orderListFormOptional.isPresent()) {
                    if (aduAuditListForm.getPageNO() == null || aduAuditListForm.getPageNO() == 0) {
                        aduAuditListForm.setPageNO(1);
                    }
                    if (aduAuditListForm.getPageSize() == null || aduAuditListForm.getPageSize() == 0) {
                        aduAuditListForm.setPageSize(10);
                    }
                    orderQuery.setPageNo(aduAuditListForm.getPageNO());
                    orderQuery.setPageSize(aduAuditListForm.getPageSize());
                    queryMap.put("pageNo", orderQuery.getPageNo());
                    queryMap.put("pageSize", orderQuery.getPageSize());
                    queryMap.put("pageOffset", orderQuery.getPageOffset());
                }
                queryMap.put("keyword", aduAuditListForm.getKeyword());
                queryMap.put("applyType", aduAuditListForm.getApplyType());
                BizResult result = BizResult.create(auditTaskService.getGPSTaskList(queryMap), true, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
                result.setTotalCount(((List) result.getData()).size());
                if (aduAuditListForm.getPageSize() != null) {
                    result.setPageSize(aduAuditListForm.getPageSize());
                    result.setPageNo(aduAuditListForm.getPageNO());
                }
                return result;
            } catch (Exception e) {
                log.error("ERROR IN getAuditTaskList", e);
                return BizResult.create(ErrorCodeEnum.SYS_ERROR.getErrCode(), e.getMessage());
            }
        } else {
            return BizResult.create(ErrorCodeEnum.NOT_LOGIN.getErrCode(), ErrorCodeEnum.NOT_LOGIN.getErrMsg());
        }
    }


}